package cn.com.anypay.manager.miaoma.suantaiqrcode.handler;

import cn.com.anypay.manager.miaoma.suantaiqrcode.handler.impl.DefaultQrCodeHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 二维码处理器工厂
 *
 * 负责根据二维码类型返回对应的处理器
 * 遵循开闭原则，新增处理器时会自动注册到工厂中
 */
@Slf4j
@Component
public class QrCodeHandlerFactory {

    private final Map<Integer, QrCodeHandler> handlerMap = new HashMap<>();
    private QrCodeHandler defaultHandler;

    @Autowired
    private List<QrCodeHandler> handlers;

    /**
     * 初始化处理器映射
     */
    @PostConstruct
    public void initHandlers() {
        log.info("Initializing QR code handlers...");

        for (QrCodeHandler handler : handlers) {
            Integer supportedType = handler.getSupportedType();

            if (supportedType == null) {
                // 默认处理器
                if (handler instanceof DefaultQrCodeHandler) {
                    defaultHandler = handler;
                    log.info("Registered default handler: {}", handler.getHandlerName());
                }
            } else {
                // 特定类型处理器
                if (handlerMap.containsKey(supportedType)) {
                    log.warn("Duplicate handler for type {}: existing={}, new={}",
                             supportedType,
                             handlerMap.get(supportedType).getHandlerName(),
                             handler.getHandlerName());
                }
                handlerMap.put(supportedType, handler);
                log.info("Registered handler for type {}: {}", supportedType, handler.getHandlerName());
            }
        }

        log.info("QR code handler initialization completed. Registered {} specific handlers + 1 default handler",
                 handlerMap.size());
    }

    /**
     * 根据二维码类型获取对应的处理器
     *
     * @param qrCodeType 二维码类型
     * @return 处理器实例，如果没有找到特定处理器则返回默认处理器
     */
    public QrCodeHandler getHandler(Integer qrCodeType) {
        if (qrCodeType == null) {
            log.debug("QR code type is null, using default handler");
            return getDefaultHandler();
        }

        QrCodeHandler handler = handlerMap.get(qrCodeType);
        if (handler != null) {
            log.debug("Found specific handler for type {}: {}", qrCodeType, handler.getHandlerName());
            return handler;
        }

        log.debug("No specific handler found for type {}, using default handler", qrCodeType);
        return getDefaultHandler();
    }

    /**
     * 获取默认处理器
     *
     * @return 默认处理器实例
     */
    private QrCodeHandler getDefaultHandler() {
        if (defaultHandler == null) {
            log.error("Default handler is not initialized!");
            throw new IllegalStateException("Default QR code handler is not available");
        }
        return defaultHandler;
    }

    /**
     * 获取所有已注册的处理器类型
     *
     * @return 处理器类型列表
     */
    public Map<Integer, String> getSupportedTypes() {
        Map<Integer, String> supportedTypes = new HashMap<>();
        for (Map.Entry<Integer, QrCodeHandler> entry : handlerMap.entrySet()) {
            supportedTypes.put(entry.getKey(), entry.getValue().getHandlerName());
        }
        return supportedTypes;
    }

    /**
     * 检查是否支持特定类型
     *
     * @param qrCodeType 二维码类型
     * @return 是否支持
     */
    public boolean isTypeSupported(Integer qrCodeType) {
        return qrCodeType != null && handlerMap.containsKey(qrCodeType);
    }
}